<?php
namespace addons\food\library;

use app\common\model\Setting as SettingModel;
use app\common\model\food\Setting;
use app\common\model\food\Order as OrderModel;
use app\common\model\food\OrderDelivery as OrderDeliveryModel;
use app\common\model\food\Table as TableModel;
use hema\wechat\Pay as WxPay;
use think\facade\Cache;

class Order
{
    private $model;
    private $applet_id;

    /**
     * 构造函数
     */
    public function __construct(int $applet_id)
    {
        $this->model = new OrderModel;
        $this->applet_id = $applet_id;
    }

    /**
     * 监听事件
     */
    public function listen()
    {
        //判断是否获取到”task_space_order“
        if (!Cache::get('event_space_order')) {
            $config = Setting::getItem('trade',$this->applet_id);
            // 未支付订单自动关闭
            $this->close($config['order']['close_time']);
            // 待配送订单自动配送完成(扫码)
            $this->table($config['order']['delivery_time']);
            // 待配送订单自动配送完成(排号)
            $this->row($config['order']['delivery_time']);
            // 待配送订单自动配送完成(外卖)
            $this->waimai($config['order']['delivery_time']);
            // 待配送订单自动配送完成(自取)
            $this->ziqu($config['order']['delivery_time']);
            //配送完成订单用户自动确认收货
            $this->receive($config['order']['receive_time']);
            //收货订单自动评价
            $this->cmt($config['order']['cmt_time']);
            // 退款订单自动退款
            $this->refund($config['order']['refund_time']);
            Cache::set('event_space_order', time(), $config['order']['time']*60);//有效期N分钟
        }
        return true;
    }  

    /**
     * 退款订单自动完成退款
     */
    private function refund($refund_time)
    {
        if ($refund_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$refund_time * 60); //分钟
        //条件
        $filter = [
            'pay_status' => 20,
            'receipt_status' => 10,
            'refund_status' => 10,
            'order_status' => 40,
            'applet_id' => $this->applet_id
        ];
        // 查询截止时间未支付的订单
        $orderIds = $this->model->where($filter)->where('refund_time','<',$deadlineTime)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            for($n=0;$n<sizeof($orderIds);$n++){
                $order = OrderModel::detail($orderIds[$n]);
                $order->refund(1);//同意退款
            }
        }
        return true;
    }

     /**
     * 未支付订单自动关闭
     */
    private function close($close_time)
    {
        // 取消n小时以前的的未付款订单
        if ($close_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$close_time * 60);   //分钟
        // 条件
        $filter = [
            'pay_status' => 10,
            'order_status' => 10,
            'applet_id' => $this->applet_id
        ];
        // 查询截止时间未支付的订单
        $orderIds = $this->model->where($filter)->where('create_time','<',$deadlineTime)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            for($n=0;$n<sizeof($orderIds);$n++){
                $order = OrderModel::detail($orderIds[$n]);
                if($order['table_id'] > 0 AND $order['order_mode']['value'] == 10){
                    $table = TableModel::get($order['table_id']);
                    $table->status = 10;
                    $table->save();
                }
                $order->save(['order_status' => 20]);
            }
        }
        return true;
    }

    /**
     * 已接订单自动完成配送（堂食扫码）
     */
    private function table($delivery_time)
    {
        // 订单配送n小时后自动完成配送
        if ($delivery_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$delivery_time * 60);
        //堂食扫码
        $filter = [
            'order_mode' => 10,
            'shop_status' => 20, //商家已接单
            'delivery_status' => 10,
            'order_status' => 10,
            'applet_id' => $this->applet_id
        ];
        // 查询截止时间未完成配送的订单
        $orderIds = $this->model->where($filter)->where('row_no','')->where('pay_status','>',10)->where('shop_time','<',$deadlineTime)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            //循环发送配送完成订阅消息
            for($n=0;$n<sizeof($orderIds);$n++){
                food_post_tpl('finish',$orderIds[$n]);
            }
            return $this->model->where('order_id','in',$orderIds)->save([
                'delivery_status' => 30,
                'delivery_time' => time()
            ]);
        }
        return true;
    }

    /**
     * 已接订单自动完成配送（堂食排号）
     */
    private function row($delivery_time)
    {
        // 订单配送n小时后自动完成配送
        if ($delivery_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$delivery_time * 60);
        //条件
        $filter = [
            'order_mode' => 10,
            'shop_status' => 20,
            'delivery_status' => 10,
            'order_status' => 10,
            'applet_id' => $this->applet_id
        ];
        // 查询截止时间未完成配送的订单
        $orderIds = $this->model->where($filter)->where('row_no','<>','')->where('pay_status','>',10)->where('shop_time','<',$deadlineTime)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            //循环发送取餐提醒订阅消息
            for($n=0;$n<sizeof($orderIds);$n++){
                food_post_tpl('take',$orderIds[$n]);
            }
            return $this->model->where('order_id','in',$orderIds)->save([
                'delivery_status' => 30,
                'delivery_time' => time()
            ]);
        }
        return true;
    }

    /**
     * 待配送订单自动配送完成（外卖）
     */
    private function waimai($delivery_time)
    {
        // 订单配送n小时后自动完成配送
        if ($delivery_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$delivery_time * 60);
        //条件
        $filter = [
            'order_mode' => 20,
            'shop_status' => 30,
            'delivery_status' => 20,
            'order_status' => 10,
            'applet_id' => $this->applet_id
        ];
        // 查询截止时间未完成配送的订单
        $orderIds = $this->model->where($filter)->where('pay_status','>',10)->where('delivery_time','<',$deadlineTime)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            //循环发送配送完成提醒订阅消息
            for($n=0;$n<sizeof($orderIds);$n++){
                food_post_tpl('delivery',$orderIds[$n]);
            }
            $deliveryModel = new OrderDeliveryModel;
            $deliveryModel->where('order_id','in',$orderIds)->save([
                'delivery_status' => 50,
                'delivery_time' => time()
            ]);
            return $this->model->where('order_id','in',$orderIds)->save([
                'delivery_status' => 30,
                'delivery_time' => time()
            ]);
        }
        return true;
    }

    /**
     * 已接订单自动完成配送（自取）
     */
    private function ziqu($delivery_time)
    {
        // 订单配送n小时后自动完成配送
        if ($delivery_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$delivery_time * 60);
        //条件
        $filter = [
            'order_mode' => 30,
            'shop_status' => 20,
            'delivery_status' => 10,
            'order_status' => 10,
            'applet_id' => $this->applet_id
        ];
        // 查询截止时间未完成配送的订单
        $orderIds = $this->model->where($filter)->where('pay_status','>',10)->where('arrive_time','<',$deadlineTime)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            //循环发送取餐提醒订阅消息
            for($n=0;$n<sizeof($orderIds);$n++){
                food_post_tpl('take',$orderIds[$n]);
            }
            return $this->model->where('order_id','in',$orderIds)->save([
                'delivery_status' => 30,
                'delivery_time' => time()
            ]);
        }
        return true;
    }

    /**
     * 已配送订单自动确认收货
     */
    private function receive($receive_time)
    {
        if ($receive_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$receive_time * 60); //分钟
        //条件
        $filter = [
            'pay_status' => 20, //非后付费有效
            'delivery_status' => 30,
            'receipt_status' => 10,
            'order_status' => 10,
            'applet_id' => $this->applet_id
        ];
        // 查询截止时间未支付的订单
        $orderIds = $this->model->where($filter)->where('delivery_time','<',$deadlineTime)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            //循环发送完成订阅消息
            for($n=0;$n<sizeof($orderIds);$n++){
                food_post_tpl('finish',$orderIds[$n]);
            }
            //更新餐桌状态
            for($n=0;$n<sizeof($orderIds);$n++){
                $order = OrderModel::detail($orderIds[$n]);
                if($order['table_id']>0){
                    $table = TableModel::get($order['table_id']);
                    $table->status = 10;
                    $table->save();
                }
                //账单分账
                $wxpay = new WxPay(SettingModel::getItem('wxpay',$order['applet_id']));
                $wxpay->divide($order);//进行分账      
            }
            $this->model->where('order_id','in',$orderIds)->save([
                'receipt_status' => 20,
                'receipt_time' => time(),
                'order_status' => 30
            ]);
        }
        return true;
    }

    /**
     * 已收货订单自动评价
     */
    private function cmt($cmt_time)
    {
        if ($cmt_time < 1) {
            return false;
        }
        // 截止时间
        $deadlineTime = time() - ((int)$cmt_time * 60); //分钟
        //条件
        $filter = [
            'is_cmt' => 0,
            'receipt_status' => 20,
            'order_status' => 30,
            'applet_id' => $this->applet_id
        ];
        // 查询截止时间未支付的订单
        $orderIds = $this->model->where($filter)->where('receipt_time','<',$deadlineTime)->column('order_id');
        // 直接更新
        if (!empty($orderIds)) {
            //更新餐桌状态
            for($n=0;$n<sizeof($orderIds);$n++){
                $order = OrderModel::detail($orderIds[$n]);
                $order->comment()->save([
                    'serve' => 5,
                    'speed' => 5,
                    'flavor' => 5,
                    'ambient' => 5,
                    'user_id' => $order['user_id'],
                    'shop_id' => $order['shop_id'],
                    'applet_id' => $order['applet_id']
                ]);
                $order->save(['is_cmt' => 1]);
            }
        }
        return true;
    }

}
